package com.topdt.jbpm.web.struts.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.util.AppContext;
import com.topdt.jbpm.identity.Department;
import com.topdt.jbpm.identity.IdFactory;
import com.topdt.jbpm.identity.IdentityService;
import com.topdt.jbpm.identity.Role;
import com.topdt.jbpm.identity.User;
import com.topdt.jbpm.model.AppAuthority;
import com.topdt.jbpm.model.AppType;
import com.topdt.jbpm.model.Application;
import com.topdt.jbpm.service.AppAuthorityService;
import com.topdt.jbpm.service.AppTypeService;
import com.topdt.jbpm.service.ApplicationService;
import com.topdt.jbpm.service.JbpmService;
import com.topdt.jbpm.web.SessionUserUtil;
@Namespace(value = "/workorder")
@Action(value = "draft",
		results = {
		@Result(name = "sucess", location = "/workflow/draftWork/applist.jsp"),
		@Result(name = "listAppsByProPSet", location = "/workflow/draftWork/applist_someBySet.jsp"),
		@Result(name = "listAppsByTypeName", location = "/workflow/draftWork/applist_oneAppType.jsp")
		},
		interceptorRefs = {
		@InterceptorRef("topDtStack"),
		@InterceptorRef(value = "pageInterceptor", params = {"includeMethods", "listAppsByTypeName"})
		}
)
@Controller
@Scope("prototype")
public class DraftAction{

	protected final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private AppAuthorityService appAuthorityService;
	@Autowired
	private ApplicationService applicationService;
	@Autowired
	private AppTypeService appTypeService;

	private JbpmService jbpmService  = JbpmService.getJbpmService();
	private IdentityService identityService = IdFactory.getIdentityServiceFactory().getIdentityService();

	private String draftType;
	private String appTypeName;//fengjinshou 20151222 应用类型名称
	private List<AppType> appTypes ;
	private List<String> showOfficeDocTypes;

	public String listApps(){
		logger.debug("<进入>:listApps方法");
		try {
			appTypes = jbpmService.findAllAppType();
			for(AppType at:appTypes){
				Set<Application> appResult = new TreeSet<Application>();
				Set<Application> apps = at.getApps();
				if("ticket".equalsIgnoreCase(draftType)){
					for(Application app : apps){
						if("0".equals(app.getIsValid())||"0".equals(app.getIsComplete())) continue;
						if(Application.APPATTR_FORM.equals(app.getAppAttr())
								||Application.APPATTR_CUSTOM_FORM.equals(app.getAppAttr())
								|| Application.APPATTR_CUSTOM_FORM_OPINION.equals(app.getAppAttr())){
							if(this.verifyAuthority(app.getAppId())) appResult.add(app);
						}
					}
				}else if("document".equalsIgnoreCase(draftType)){
					for(Application app:apps){
						if("0".equals(app.getIsValid())||"0".equals(app.getIsComplete())) continue;
						if(Application.APPATTR_DOC.equals(app.getAppAttr())
								|| Application.APPATTR_CUSTOM_DOC.equals(app.getAppAttr())
								|| Application.APPATTR_CUSTOM_DOC_OPINION.equals(app.getAppAttr())){
							if(this.verifyAuthority(app.getAppId())) appResult.add(app);
						}
					}
				}
				at.setApps(new TreeSet<Application>(apps));
			}
		} catch (Exception e) {
			logger.error("<错误>:获取list失败",e);
		}
		return "sucess";
	}

	/**
	 * 通过属性文件的设置获取相关应用
	 * @author 冯晋首
	 * @date   2015年12月23日 下午4:45:25
	 * @return
	 */
	public String listAppsByProPSet(){
		logger.debug("<进入>:listAppsByProPSet方法   通过属性文件的设置获取相关应用");
		try {
			appTypes = jbpmService.findAllAppType();
			for(AppType at:appTypes){
				Set<Application> appResult = new TreeSet<Application>();
				Set<Application> apps = at.getApps();
				if("ticket".equalsIgnoreCase(draftType)){
					for(Application app : apps){
						if("0".equals(app.getIsValid())||"0".equals(app.getIsComplete())) continue;
						if(Application.APPATTR_FORM.equals(app.getAppAttr())
								||Application.APPATTR_CUSTOM_FORM.equals(app.getAppAttr())
								|| Application.APPATTR_CUSTOM_FORM_OPINION.equals(app.getAppAttr())){
							if(this.verifyAuthority(app.getAppId())) appResult.add(app);
						}
					}
				}else if("document".equalsIgnoreCase(draftType)){
					for(Application app:apps){
						if("0".equals(app.getIsValid())||"0".equals(app.getIsComplete())) continue;
						if(Application.APPATTR_DOC.equals(app.getAppAttr())
								|| Application.APPATTR_CUSTOM_DOC.equals(app.getAppAttr())
								|| Application.APPATTR_CUSTOM_DOC_OPINION.equals(app.getAppAttr())){
							if(this.verifyAuthority(app.getAppId())) appResult.add(app);
						}
					}
				}
				at.setApps(new TreeSet<Application>(appResult));
			}
			//fengjinshou 20151221 获取要显示公文应用类型 -------start
			String officeDocTypes = AppContext.getProperties("showOfficeDocTypes");
			if(StringUtils.isNotBlank(officeDocTypes)){
				showOfficeDocTypes = new ArrayList<String>();
				if(officeDocTypes.indexOf(",")!=-1){
					String[] officeDocTypesArr =  officeDocTypes.split(",");
					for (String OfficeDocTypeStr : officeDocTypesArr) {
						showOfficeDocTypes.add(OfficeDocTypeStr.trim());
					}
				}else{
					showOfficeDocTypes.add(officeDocTypes.trim());
				}
			}

		} catch (Exception e) {
			logger.error("<错误>:通过属性文件的设置获取相关应用失败",e);
		}
		return "listAppsByProPSet";
	}


	/**
	 * 通过类型获取应用
	 * @author 冯晋首
	 * @date   2015年12月22日 下午5:27:49
	 * @return
	 */
	public String listAppsByTypeName(){
		logger.debug("<进入>:listAppsByTypeName方法   通过类型获取应用");
		try {
			if(StringUtils.isNotBlank(appTypeName)){
				appTypes = appTypeService.findByName(appTypeName.trim());
				for(AppType at:appTypes){
					Set<Application> appResult = new TreeSet<Application>();
					Set<Application> apps = at.getApps();
					if("ticket".equalsIgnoreCase(draftType)){
						for(Application app : apps){
							if("0".equals(app.getIsValid())||"0".equals(app.getIsComplete())) continue;
							if(Application.APPATTR_FORM.equals(app.getAppAttr())
									||Application.APPATTR_CUSTOM_FORM.equals(app.getAppAttr())
									|| Application.APPATTR_CUSTOM_FORM_OPINION.equals(app.getAppAttr())){
								appResult.add(app);
							}
						}
					}else if("document".equalsIgnoreCase(draftType)){
						for(Application app:apps){
							if("0".equals(app.getIsValid())||"0".equals(app.getIsComplete())) continue;
							if(Application.APPATTR_DOC.equals(app.getAppAttr())
									|| Application.APPATTR_CUSTOM_DOC.equals(app.getAppAttr())
									|| Application.APPATTR_CUSTOM_DOC_OPINION.equals(app.getAppAttr())){
								appResult.add(app);
							}
						}
					}
					at.setApps(new TreeSet<Application>(appResult));
				}
			}
		} catch (Exception e) {
			logger.error("<错误>:通过类型获取应用失败",e);
		}
		return "listAppsByTypeName";
	}

	private boolean verifyAuthority(String appId){
		logger.debug("<进入>:verifyAuthority方法");
		//if(!applicationService.judgeApp(appId)) return false;
		//得到当前登录用户及其所在的部门和角色
		User user  = SessionUserUtil.getCurrentUser();

		List<Department> dep = identityService.getDepsOfUser(user.getId());
		List<Role> role = identityService.getRolesOfUser(user.getId());

		//得到该App所具有的权限
		String perAuthorIds = "";
		String deptAuthorIds = "";
		String roleAuthorIds = "";
		Map<String,AppAuthority> appAuthorityMap = appAuthorityService.getAuthorityMapByAppId(appId);
		if(appAuthorityMap!=null&&appAuthorityMap.size()>0){
			if(appAuthorityMap.get(AppAuthority.TYPE_PER)!=null){
				perAuthorIds = appAuthorityMap.get(AppAuthority.TYPE_PER).getAuthorityData();
				if(perAuthorIds!=null&&!perAuthorIds.isEmpty()&&perAuthorIds.contains(user.getId()))
					return true;
			}
			if(appAuthorityMap.get(AppAuthority.TYPE_DEPT)!=null){
				deptAuthorIds = appAuthorityMap.get(AppAuthority.TYPE_DEPT).getAuthorityData();
				if(dep!=null&&dep.size()>0){
					for(Department dm: dep){
						if(dm.getId()==null)continue;
						if(deptAuthorIds!=null&&!deptAuthorIds.isEmpty()&&deptAuthorIds.contains(dm.getId()))
							return true;
					}
				}
			}
			if(appAuthorityMap.get(AppAuthority.TYPE_ROLE)!=null){
				roleAuthorIds = appAuthorityMap.get(AppAuthority.TYPE_ROLE).getAuthorityData();
				if(role!=null&&role.size()>0){
					for(Role r:role){
						if(roleAuthorIds!=null&&!roleAuthorIds.isEmpty()&&roleAuthorIds.contains(r.getId()))
							return true;
					}
				}
			}
		}
		return false;
	}
	public List<AppType> getAppTypes() {
		return appTypes;
	}

	public void setAppTypes(List<AppType> appTypes) {
		this.appTypes = appTypes;
	}

	public String getDraftType() {
		return draftType;
	}

	public void setDraftType(String draftType) {
		this.draftType = draftType;
	}
	public AppAuthorityService getAppAuthorityService() {
		return appAuthorityService;
	}
	public void setAppAuthorityService(AppAuthorityService appAuthorityService) {
		this.appAuthorityService = appAuthorityService;
	}
	public List<String> getShowOfficeDocTypes() {
		return showOfficeDocTypes;
	}
	public void setShowOfficeDocTypes(List<String> showOfficeDocTypes) {
		this.showOfficeDocTypes = showOfficeDocTypes;
	}

	public String getAppTypeName() {
		return appTypeName;
	}

	public void setAppTypeName(String appTypeName) {
		this.appTypeName = appTypeName;
	}

}



